# coding: utf-8
# timer 多线程

import time, signal, sys
from threading import Thread


# 循环次数:永远
LOOP_FOREVER = -9999

# 主循环的时间间隔 秒
THREAD_LOOP_INTERVAL = 0.1

# Timer线程
thread = None

# 注册的Timer
data = {}

# timer序号
next_id = 0


class TimerThread(Thread):
    
    def __init__(self):
        self.stopped = False
        Thread.__init__(self)

    def run(self):
        while not self.stopped:
            threading_loop()
            time.sleep(THREAD_LOOP_INTERVAL)


class Timer():
    def __init__(self, interval, callback, loops):
        self.cur_time = 0
        self.interval = interval
        self.callback = callback
        self.loops = loops


def init():
    # 多线程退出 注册信号量 ctrl+c
    signal.signal(signal.SIGINT, sigint_handler)
    
    global thread
    thread = TimerThread()
    thread.setDaemon(True)  # True: 跟随主线程停止
    thread.start()


# 信号处理
def sigint_handler(signum, frame): 
    print "signal.SIGINT (you pressed Ctrl+C)"
    stop()
    sys.exit()


def stop():
    global thread
    thread.stopped = True
    thread.join()


def threading_loop():
    global data
    to_del = []

    for id, t in data.iteritems():
        t.cur_time += THREAD_LOOP_INTERVAL
        if t.cur_time >= t.interval:
            t.cur_time = t.cur_time - t.interval
            # 调用回调
            t.callback()

            if t.loops != LOOP_FOREVER:
                t.loops -= 1
                if t.loops <= 0:
                    to_del.append(id)

    for id in to_del:
        stop_timer(id)


# 创建一个Timer 秒
def create_timer(interval, callback, loops=LOOP_FOREVER):
    global data
    if loops < 0 and loops != LOOP_FOREVER: return

    t = Timer(interval, callback, loops)
    id = _get_next_id()
    data[id] = t
    return id


# 移除一个Timer
def stop_timer(id):
    t = data.pop(id)


def _get_next_id():
    global next_id
    res = next_id
    next_id += 1
    return res





